﻿using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace RabbitmqConsumer
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("开启启动rabbitmq的订阅监听");
            var conFactory = new ConnectionFactory//创建连接工厂对象
            {
                HostName = "113.141.88.219",//IP地址
                Port = 5672,//端口号
                UserName = "guest",//用户账号
                Password = "ym123!@#"//用户密码
            };

            using var con = conFactory.CreateConnection();
            using var channel = con.CreateModel();
            var queueName = "queue";
            //声明一个队列
            channel.QueueDeclare(
                queue: queueName,//消息队列名称
                durable: false,//是否持久化
                exclusive: false,
                autoDelete: false,
                arguments: null
            );
            //创建消费者对象
            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                Console.WriteLine(model);
                var message = ea.Body;//接收到的消息
                Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message.ToArray()));
                channel.BasicAck(ea.DeliveryTag,true);
            };
            //消费者开启监听
            channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);
            Console.ReadKey();
        }
    }
}